<?php

namespace app\admin\model\course;

use think\Model;
use traits\model\SoftDelete;

class UserSection extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'user_section';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'studytime_text',
        'check_status_text',
        'study_status_text'
    ];


    public function getCheckStatusList()
    {
        return ['0' => __('Check_status 0'), '1' => __('Check_status 1')];
    }

    public function getStudyStatusList()
    {
        return ['0' => __('正在学习'), '1' => __('完成学习')];
    }


    public function getStudytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['studytime']) ? $data['studytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStudyStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['study_status']) ? $data['study_status'] : '');
        $list = $this->getStudyStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setStudytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public static function getUserSectionTime($coursecontent_id = null, $user_id = null)
    {
        $section_list = Section::all(['coursecontent_id' => $coursecontent_id]);
        $study_time = 0;
        foreach ($section_list as $v){
            $data = self::get(['section_id' => $v->id]);
            if($data){
                $study_time += $data->studytime;
            }
        }
        return $study_time;
    }

    public function section()
    {
        return $this->belongsTo('Section', 'section_id', 'id', [], 'LEFT')->bind(['videofile','section_name' => 'name']);
    }

    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->bind(['nickname']);
    }
}
